import axios from 'axios'
import qs from 'qs'

interface SUCCESSFUL {
  status: number
  message?: object[] | object | string
}
console.log(process.env.url)
const baseURL = process.env.NODE_ENV === 'development' ? '/api' : process.env.url
// 基本配置
const service = axios.create({
  // baseURL: 'http://localhost:8080',
  baseURL: baseURL,
  timeout: 5000,
})

service.interceptors.request.use(
  config => {
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = <SUCCESSFUL> response.data
    if (res.status !== 0) {
      return Promise.reject(new Error(res.message as string || 'Error'))
    } else {
      return res
    }
  },
  error => {
    return Promise.reject(error)
  }
)

export function get(url: string,params: object) {
  return new Promise((resolve,reject) => {
    service.get(url,{
          params:params
      }).then(res => {
          resolve(res)
      }).catch(err => {
          reject(err)
      })
  })
} 

export function post(url: string,params: object) {
  return new Promise((resolve,reject)=> {
    service.post(url,qs.stringify(params)).then(res=> {
          resolve(res)
      }).catch(err => {
          reject(err)
      } )
  })
}
